import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from './router';
import store from './store';
import App from './App.vue';
import Cookie from 'js-cookie';
import axios from 'axios';
import '@fortawesome/fontawesome-free/css/all.css';
import ChatDatabase from './network/chat/chatDatabase'; // indexedDB，用于本地存储消息
import config from './config'; // 导入配置文件

Vue.config.productionTip = false;
Vue.prototype.axios = axios;
// 将配置挂载到 Vue 原型上
Vue.prototype.$config = config;
Vue.use(ElementUI);

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = Cookie.get('token');

    if (!token && to.name !== 'login') {
        next({ name: 'login' });
    } else if (token && to.name === 'login') {
        next({ name: 'home' });
    } else {
        next();
    }
});

async function initApplication() {
    try {
        // 初始化 WebSocket 连接
        await store.dispatch('websocket/initWebSocket');

        // 初始化聊天数据库
        const chatDb = await initChatDatabase('huang'); // 替换为实际获取用户 ID 的逻辑
        Vue.prototype.$chatDb = chatDb; // 挂载到 Vue 原型链上

        // 创建并挂载 Vue 实例
        new Vue({
            router,
            store,
            render: h => h(App),
        }).$mount('#app');
    } catch (error) {
        console.error('Failed to initialize application:', error);
    }
}

function initChatDatabase(userId) {
    const chatDatabase = new ChatDatabase(userId);
    return chatDatabase.init().then(() => chatDatabase);
}

// 启动应用
initApplication();